package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class demo9TcpEchoServer {
    ServerSocket serverSocket = null;
    public demo9TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务端启动");
        while(true){
            ExecutorService pool = Executors.newFixedThreadPool(10);
            pool.submit(() -> {
                Socket clientSocket = null;
                try {
                    clientSocket = serverSocket.accept();
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner sc = new Scanner(inputStream);
            //从客户端接受请求
            while(true){
                if(!sc.hasNext()){
                    System.out.println("服务器下线");
                    break;
                }
                String request = sc.next();
                //计算响应
                String respond = process(request);
                //将响应写回客户端
                PrintWriter writer = new PrintWriter(outputStream);
                //这里的写方式要与读方式相同，以分隔符为界限划分字段
                writer.println(respond);
                writer.flush();
                System.out.printf("[%s:%d], req=%s resp=%s", clientSocket.getInetAddress(),
                                 clientSocket.getPort(), request, respond);
            }
        }catch (IOException e){
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }
    public String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        demo9TcpEchoServer demo9TcpEchoServer = new demo9TcpEchoServer(9090);
        demo9TcpEchoServer.start();
    }
}
